<!-- #layout name=default -->
<div id="main" class="fixed" v-cloak>
  <div class="heander-panel">
    <div class="page-header">
      <template v-if="isNewPage">
        <h1 class="title pull-left">{{Kooboo.text.common.Page + ': '}}</h1>
        <div class="form-group pull-left" :class="{'has-error':nameError}">
          <input
            v-kb-tooltip:right.manual.error="nameError"
            type="text"
            placeholder="name"
            class="input-large form-control"
            v-model="name"
            @input="valid"
            @blur="nameInputBlur"
          />
        </div>
      </template>

      <h1 class="title pull-left" v-else>
        <span>{{Kooboo.text.common.Page + ': '}}</span>
        <strong :title="name">{{name}}</strong>
      </h1>

      <kb-multilang-selector
        v-if="multiLangs"
        v-show="curType == 'preview'"
        :cultures="multiLangs.cultures"
        :default-culture="multiLangs.default"
      ></kb-multilang-selector>
      <button
        v-show="pageContent && curType == 'code'"
        @click="formatCode"
        type="button"
        class="btn btn-default pull-right"
        >Format code</button
      >
    </div>
  </div>
  <kb-page-widget-meta
    v-if="multiLangs"
    :multi-langs="multiLangs"
  ></kb-page-widget-meta>
  <div class="block-fullpage with-buttons">
    <div class="block-visual-editor default">
      <div class="tabs-bottom">
        <div class="tab-content">
          <section class="tab-pane" :class="{active: curType == 'preview'}">
            <div class="kb-editor" style="overflow: hidden">
              <iframe
                src="about:blank"
                id="page_iframe"
                class="kb-iframe"
              ></iframe>
            </div>
            <div class="kb-panel">
              <ul class="nav nav-tabs">
                <li class="active">
                  <a href="#layout_design" data-toggle="tab">Design</a>
                </li>
                <li>
                  <a href="#page_setting" data-toggle="tab">Settings</a>
                </li>
              </ul>
              <div class="tab-content">
                <section id="layout_design" class="tab-pane active">
                  <div class="panel-group">
                    <kb-page-positions></kb-page-positions>
                  </div>
                </section>
                <section id="page_setting" class="tab-pane">
                  <div class="panel-group">
                    <kb-page-basic-settings
                      v-if="settings&&multiLangs"
                      :settings="settings"
                      :multi-langs="multiLangs"
                    >
                    </kb-page-basic-settings>
                    <kb-page-html-meta
                      v-if="settings&&multiLangs"
                      :settings="settings"
                      :default-lang="multiLangs.default"
                    >
                    </kb-page-html-meta>
                    <kb-page-parameters
                      v-if="settings"
                      :parameters="settings.parameters"
                    >
                    </kb-page-parameters>
                    <div>
                      <div class="panel panel-default">
                        <div
                          class="panel-heading clickable"
                          data-toggle="collapse"
                          data-target="#J_Setting_Styles"
                        >
                          <h4 class="panel-title">Styles</h4>
                        </div>
                        <div
                          id="J_Setting_Styles"
                          class="panel-collapse collapse"
                        >
                          <ul
                            class="list-group"
                            v-kb-sortable="bindingPanel.styleList"
                            @after-sort="bindingPanel.styleSorted"
                          >
                            <li
                              v-for="(item,index) in bindingPanel.styleList"
                              :key="index"
                              class="list-group-item"
                            >
                              <span class="sortable"
                                ><i class="glyphicon glyphicon-list"></i
                              ></span>
                              <a
                                class="btn gray btn-xs pull-right margin-right-5"
                                href="javascript:;"
                                title="Remove"
                                v-kb-tooltip:top="Kooboo.text.common.remove"
                                @click="removeStyle(item)"
                                ><i class="fa fa-minus"></i
                              ></a>
                              <a
                                v-if="item.text"
                                class="btn blue btn-xs pull-right"
                                href="javascript:;"
                                title="Edit"
                                v-kb-tooltip:top="Kooboo.text.common.edit"
                                @click="editJsCss(item)"
                                ><i class="fa fa-pencil"></i
                              ></a>
                              <span class="nowrap-text">{{item.name}}</span>
                            </li>
                          </ul>
                          <div class="panel-body">
                            <button
                              type="button"
                              class="btn blue btn-xs pull-right"
                              @click="createStyle"
                              ><i class="fa fa-plus"></i
                            ></button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div class="panel panel-default">
                        <div
                          class="panel-heading clickable"
                          data-toggle="collapse"
                          data-target="#J_Setting_Scripts"
                        >
                          <h4 class="panel-title">Scripts</h4>
                        </div>
                        <div
                          id="J_Setting_Scripts"
                          class="panel-collapse collapse"
                        >
                          <ul
                            class="list-group"
                            v-kb-sortable="bindingPanel.bodyScriptList"
                            @after-sort="bindingPanel.bodyScriptSorted"
                            style="min-height: 40px"
                          >
                            <li
                              class="list-group-item"
                              v-for="(item,index) in bindingPanel.bodyScriptList"
                            >
                              <span class="sortable"
                                ><i class="glyphicon glyphicon-list"></i
                              ></span>
                              <a
                                class="btn gray btn-xs pull-right margin-right-5"
                                href="javascript:;"
                                title="Remove"
                                v-kb-tooltip:top="Kooboo.text.common.remove"
                                @click="removeScript(item)"
                                ><i class="fa fa-minus"></i
                              ></a>
                              <a
                                v-if="item.text"
                                class="btn blue btn-xs pull-right"
                                href="javascript:;"
                                title="Edit"
                                v-kb-tooltip:top="Kooboo.text.common.edit"
                                @click="editJsCss(item)"
                                ><i class="fa fa-pencil"></i
                              ></a>
                              <span class="nowrap-text">{{item.name}}</span>
                            </li>
                          </ul>
                          <div class="panel-body">
                            <button
                              type="button"
                              class="btn blue btn-xs pull-right"
                              @click="createScript(false)"
                              ><i class="fa fa-plus"></i
                            ></button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div class="panel panel-default">
                        <div
                          class="panel-heading clickable"
                          data-toggle="collapse"
                          data-target="#J_Setting_Cache"
                        >
                          <h4 class="panel-title">Cache</h4>
                        </div>
                        <div
                          id="J_Setting_Cache"
                          class="panel-collapse collapse"
                        >
                          <div class="panel-body">
                            <div
                              style="
                                display: flex;
                                align-items: center;
                                margin: 8px 0;
                              "
                            >
                              <label class="control-label"
                                ><span>Enable cache</span></label
                              >
                              <div style="flex: 1"></div>
                              <kb-switch v-model="enableCache"></kb-switch>
                            </div>
                            <div
                              style="
                                display: flex;
                                align-items: center;
                                margin: 8px 0;
                              "
                              v-if="enableCache"
                            >
                              <label class="control-label"
                                ><span>Cache by version</span></label
                              >
                              <div style="flex: 1"></div>
                              <kb-switch v-model="cacheByVersion"></kb-switch>
                            </div>

                            <div v-if="enableCache&&!cacheByVersion">
                              <span style="display: block; padding: 5px"
                                >Time</span
                              >
                              <div class="input-group">
                                <input
                                  class="form-control"
                                  type="number"
                                  v-model="cacheMinutes"
                                />
                                <div class="input-group-addon">Minutes</div>
                              </div>
                            </div>
                            <div v-if="enableCache">
                              <span style="display: block; padding: 5px"
                                >Cache query keys</span
                              >
                              <input
                                class="form-control"
                                v-model="cacheQueryKeys"
                                placeholder="Example: category,page,index"
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </section>
              </div>
            </div>
          </section>
          <section class="tab-pane" :class="{active: curType == 'code'}">
            <kb-code-editor
              :code.sync="pageContent"
              auto-size
              lang="html"
              ref="codeEditor"
            ></kb-code-editor>
          </section>
        </div>
        <ul class="nav nav-tabs">
          <li
            :class="{active: curType == 'preview'}"
            @click="changeType('preview')"
          >
            <a href="javascript:;">Preview</a>
          </li>
          <li :class="{active: curType == 'code'}" @click="changeType('code')">
            <a href="javascript:;">Source code</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <div class="page-buttons">
    <div class="btn-group dropup">
      <button class="btn green" style="margin: 0" @click="onSaveAndReturn"
        >Save &amp; Return</button
      >
      <a
        class="btn green dropdown-toggle"
        data-toggle="dropdown"
        style="margin: 0; min-width: auto"
      >
        <i class="fa fa-angle-up"></i>
      </a>
      <ul class="dropdown-menu" role="menu">
        <li><a href="javascript:;" @click="onSave">Save</a></li>
      </ul>
    </div>
    <a href="javascript:;" @click="userCancel" class="btn gray">Cancel</a>
  </div>
  <kb-layout-style-script></kb-layout-style-script>
  <kb-page-widget-component-selector></kb-page-widget-component-selector>
</div>

<script>
  Kooboo.pageEditor = {
    component: {},
    store: {},
    util: {},
    viewModel: {},
    widget: {},
  };
</script>
<script>
  (function () {
    Kooboo.loadJS([
      "/_Admin/Scripts/components/kb-code-editor.js",
      "/_Admin/Scripts/kooboo/Guid.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Position.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Label.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Style.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Script.js",
      "/_Admin/Scripts/pageEditor/stores/ComponentStore.js",
      "/_Admin/Scripts/layoutEditor/stores/BindingStore.js",
      "/_Admin/Scripts/layoutEditor/stores/PositionStore.js",
      "/_Admin/Scripts/layoutEditor/viewModel/BindingPanel.js",
      "/_Admin/Scripts/tool/KoobooToolTemplateManager.js",
      "/_Admin/Scripts/tool/KoobooTool.js",
      "/_Admin/Scripts/pageEditor/utils/ComponentTool.js",
      "/_Admin/Scripts/pageEditor/utils/Position.js",
      "/_Admin/Scripts/pageEditor/utils/PositionScanner.js",
      "/_Admin/Scripts/pageEditor/components/basic-settings.js",
      "/_Admin/Scripts/pageEditor/components/htmlmeta.js",
      "/_Admin/Scripts/pageEditor/components/parameters.js",
      "/_Admin/Scripts/layoutEditor/components/style-script.js",
      "/_Admin/Scripts/layoutEditor/components/KBFrame.js",
      "/_Admin/Scripts/pageEditor/components/positions.js",
      "/_Admin/Scripts/lib/bootstrap3-typeahead.min.js",
      "/_Admin/Scripts/lib/jquery.textarea_autosize.min.js",
      "/_Admin/Scripts/components/kbTypeahead.js",
      "/_Admin/Scripts/components/kbMultilangSelector.js",
      "/_Admin/Scripts/pageEditor/widgets/html-meta.js",
      "/_Admin/Scripts/lib/jstree.min.js",
      "/_Admin/Scripts/pageEditor/widgets/component-selector.js",
      "/_Admin/Scripts/lib/jquery-ui-customized.js",
      "/_Admin/Scripts/lib/js-beautify/lib/beautify-html.js",
      "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.js",
      "/_Admin/Scripts/components/kbSwitch.js",
    ]);
    Kooboo.loadCSS([
      "/_Admin/Scripts/lib/codemirror/lib/codemirror.css",
      "/_Admin/Styles/jstree/style.min.css",
      "/_Admin/Styles/bootstrap-editable/css/bootstrap-editable.css",
      "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.css",
    ]);
    window.__pageEditor = {};
    var Guid = Kooboo.Guid,
      BindingStore = Kooboo.pageEditor.store.BindingStore,
      BindingPanel = Kooboo.pageEditor.viewModel.BindingPanel,
      KBFrame = Kooboo.pageEditor.component.KBFrame,
      ComponentTool = Kooboo.pageEditor.util.ComponentTool;

    var savedStyles, savedScripts;

    var self = new Vue({
      el: "#main",
      data: function () {
        return {
          isNewPage: false,
          pageId: Kooboo.getQueryString("Id") || Kooboo.Guid.Empty,
          layoutId: Kooboo.getQueryString("layoutId"),
          kbFrame: null,
          layoutName: "",
          name: "",
          nameError: "",
          posted: false,
          bindingPanel: new BindingPanel(),
          multiLangs: null,
          curType: "preview",
          pageContent: "",
          backupPageContent: "",
          cachedPositionsInfo: null,
          positions: [],
          savedStyles: null,
          savedScripts: null,
          settings: null,
          isTitleChanged: false,
          isMetaChanged: false,
          isUrlChanged: false,
          isBodyChanged: false,
          isSaveAndReturn: false,
          submitData: null,
          enableCache: false,
          cacheByVersion: false,
          cacheMinutes: 3,
          cacheQueryKeys: "",
        };
      },
      computed: {
        isPageContentEqual: function () {
          return plainify(this.pageContent) == plainify(this.backupPageContent);

          function plainify(p) {
            var lineBreaker = p.indexOf("\r\n") > -1 ? "\r\n" : "\n";
            return p
              .split(lineBreaker)
              .map(function (line) {
                return line.trim();
              })
              .join("");
          }
        },
        isContentChanged: function () {
          var self = this;
          return (
            self.isTitleChanged ||
            self.isMetaChanged ||
            self.isUrlChanged ||
            self.isBodyChanged ||
            (self.curType == "code" ? !self.isPageContentEqual : false)
          );
        },
      },
      mounted: function () {
        var self = this;
        self.isNewPage = self.pageId == Kooboo.Guid.Empty;
        self.kbFrame = new KBFrame(document.getElementById("page_iframe"), {
          type: "layout_page",
        });
        window.__pageEditor.kbFrame = self.kbFrame;

        Kooboo.EventBus.subscribe("binding/remove", function (data) {
          if (BindingStore.byId(data.id)) {
            BindingStore.remove(data.id);
          }
        });

        $(window).on(
          "resize",
          _.debounce(function () {
            Kooboo.EventBus.publish("kb/page/layout/component/remask");
          }, 50)
        );

        Kooboo.EventBus.subscribe(
          "kb/pageeditor/component/position/ready",
          function () {
            Kooboo.EventBus.publish("fdoc/load", self.cachedPositionsInfo);
          }
        );

        Kooboo.EventBus.subscribe("kb/page/final/save", function (res) {
          if (!res.errorCount || res.errorCount == 0) {
            var styleList = [],
              scriptList = [];
            self.bindingPanel.styleList.forEach(function (style) {
              style.url && styleList.push(style.url);
            });
            self.bindingPanel.bodyScriptList.forEach(function (script) {
              script.url && scriptList.push(script.url);
            });
            res["styles"] = styleList;
            res["scripts"] = scriptList;

            res["body"] =
              self.curType == "preview"
                ? self.getSaveLayoutHTML()
                : self.pageContent;
            res["name"] = self.name;
            res["id"] = self.pageId;
            res["enableCache"] = self.enableCache;
            res["cacheByVersion"] = self.cacheByVersion;
            res["cacheMinutes"] = self.cacheMinutes;
            res["cacheQueryKeys"] = self.cacheQueryKeys;

            self.submitData = res;

            if (self.isSaveAndReturn) {
              self.onSubmit(function () {
                self.goBack();
              });
            } else {
              self.onSubmit(function (id) {
                if (self.isNewPage) {
                  location.href = Kooboo.Route.Get(
                    Kooboo.Route.Page.EditLayout,
                    {
                      id: id,
                      layoutId: self.layoutId,
                    }
                  );
                } else {
                  self.isTitleChanged = false;
                  self.isMetaChanged = false;
                  self.isUrlChanged = false;
                  self.isBodyChanged = false;
                  self.backupPageContent = self.pageContent;
                  window.info.show(Kooboo.text.info.save.success, true);
                }
              });
            }
          }
        });

        Kooboo.EventBus.subscribe("kb/page/field/change", function (data) {
          switch (data.type) {
            case "title":
              self.isTitleChanged = true;
              break;
            case "meta":
              self.isMetaChanged = true;
              break;
            case "url":
              self.isUrlChanged = true;
              break;
            case "resource":
              self.isBodyChanged = true;
              break;
          }
        });

        $.when(
          Kooboo.Page.getEdit({
            Id: self.pageId,
            layoutId: self.layoutId,
          }),
          Kooboo.Layout.get({
            Id: self.layoutId,
          }),
          Kooboo.Site.Langs(),
          Kooboo.Component.getList(),
          Kooboo.Style.getExternalList(),
          Kooboo.Script.getExternalList(),
          Kooboo.ResourceGroup.Style(),
          Kooboo.ResourceGroup.Script()
        ).then(function (
          page,
          layout,
          langs,
          component,
          styles,
          scripts,
          styleGroup,
          scriptGroup
        ) {
          var styleList = [],
            styleGroupList = [],
            scriptList = [],
            scriptGroupList = [];

          page = $.isArray(page) ? page[0] : page;
          layout = $.isArray(layout) ? layout[0] : layout;
          styles = $.isArray(styles) ? styles[0] : styles;
          scripts = $.isArray(scripts) ? scripts[0] : scripts;
          styleGroup = $.isArray(styleGroup) ? styleGroup[0] : styleGroup;
          scriptGroup = $.isArray(scriptGroup) ? scriptGroup[0] : scriptGroup;

          styles.model.forEach(function (style) {
            styleList.push({
              id: style.id,
              text: style.name,
              url: style.routeName,
            });
          });

          scripts.model.forEach(function (script) {
            scriptList.push({
              id: script.id,
              text: script.name,
              url: script.routeName,
            });
          });

          styleGroup.model.forEach(function (style) {
            styleGroupList.push({
              id: style.id,
              text: style.name,
              url: style.relativeUrl,
            });
          });

          scriptGroup.model.forEach(function (script) {
            scriptGroupList.push({
              id: script.id,
              text: script.name,
              url: script.relativeUrl,
            });
          });

          self.bindingPanel.styleResource = {
            styles: styleList,
            styleGroup: styleGroupList,
          };

          self.bindingPanel.scriptResource = {
            scripts: scriptList,
            scriptGroup: scriptGroupList,
          };

          Kooboo.pageEditor.store.ComponentStore.setTypes(component[0].model);
          self.pageContent = page.model.body || "";
          self.name = page.model.name;
          self.settings = page.model;
          self.multiLangs = langs[0].model;
          self.layoutName = layout.model.name;
          savedStyles = page.model.styles;
          savedScripts = page.model.scripts;
          self.setHTML(layout.model.body, function () {});
          self.enableCache = page.model.enableCache;
          self.cacheByVersion = page.model.cacheByVersion;
          self.cacheMinutes = page.model.cacheMinutes || 3;
          self.cacheQueryKeys = page.model.cacheQueryKeys || "";
        });

        $(window).on("resize", function () {
          Kooboo.EventBus.publish("kb/page/layout/component/remask");
        });
      },
      methods: {
        valid: function (isPosted) {
          if (!self.posted || !self.isNewPage) return true;
          var rules = [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64,
            },
          ];
          if (isPosted) {
            rules.push({
              remote: {
                url: Kooboo.Page.isUniqueName(),
                data: function () {
                  return {
                    name: self.name,
                  };
                },
              },
              message: Kooboo.text.validation.taken,
            });
          }

          var result = Kooboo.validField(self.name, rules);
          self.nameError = result.msg;
          return result.valid;
        },
        nameInputBlur: function () {
          if (!self.name) return;
          Kooboo.EventBus.publish("kb/page/url/route/set", self.name);
        },
        formatCode: function (cb) {
          self.$refs.codeEditor.formatCode(cb);
        },
        removeStyle: function (item) {
          self.bindingPanel.removeStyle(item);
        },
        editJsCss: function (item) {
          self.bindingPanel.editJsCss(item);
        },
        removeScript: function (item) {
          self.bindingPanel.removeScript(item);
        },
        createStyle: function () {
          self.bindingPanel.createStyle();
        },
        createScript: function (b) {
          self.bindingPanel.createScript(b);
        },
        getPositions: function (dom, positions, fromNestedLayout, layoutName) {
          $(dom)
            .children("placeholder")
            .each(function (idx, position) {
              var name = $(position).attr("id"),
                contents = [];

              $(
                Kooboo.pageEditor.util.ComponentTool.getComponentTags().join(
                  ","
                ),
                position
              ).each(function (idx, content) {
                if (
                  $(content).parents("placeholder").length == 1 ||
                  fromNestedLayout
                ) {
                  contents.push({
                    type: content.tagName.toLowerCase(),
                    name: $(content).attr("id"),
                    engine: content.hasAttribute("engine")
                      ? $(content).attr("engine")
                      : false,
                    id: Math.ceil(Math.random() * Math.pow(2, 53)),
                  });
                }

                if (content.tagName.toLowerCase() == "layout") {
                  positions = self.getPositions(
                    content,
                    positions,
                    true,
                    $(content).attr("id")
                  );
                }
              });

              var pos = {
                name: name,
                contents: contents,
                fromLayout: fromNestedLayout,
              };

              layoutName && (pos.layoutName = layoutName);

              positions.push(pos);
            });

          return positions;
        },
        setHTML: function (html, callback) {
          !self.kbFrame.hasResource() &&
            self.kbFrame.setResource(self.bindingPanel.resources);
          self.kbFrame.setExistResource({
            scripts: savedScripts,
            styles: savedStyles,
          });
          self.kbFrame.setContent(html, function () {
            self.bindingPanel.elem = self.kbFrame.getDocumentElement();
            if (!self.cachedPositionsInfo) {
              self.cachedPositionsInfo = {
                fdoc: self.kbFrame.getDocumentElement(),
                container: $(".kb-editor")[0],
                positions: self.positions,
                styles: savedStyles,
                scripts: savedScripts,
              };
            }

            setTimeout(function () {
              Kooboo.EventBus.publish("fdoc/load", self.cachedPositionsInfo);
              $(window).trigger("resize");
            }, 500);
            if (callback) callback();
          });
        },
        getLayoutHTML: function () {
          var vDom = $("<layout>");
          $(vDom).attr("id", self.layoutName);
          vDom = self.getLayout(self.kbFrame.getDocumentElement(), vDom);
          return vDom[0].outerHTML;
        },
        getLayout: function (node, dom) {
          dom = self.getSaveLayout(node, dom);
          handleSavedLayout(dom[0]);

          function handleSavedLayout(dom) {
            if ($(dom)[0].tagName.toLowerCase() == "placeholder") {
              if (dom.hasAttribute("k-omit")) {
                if ($(dom).children().length) {
                  var children = $(dom).children().get().reverse();
                  children.forEach(function (child) {
                    $(child).insertAfter(dom);
                  });
                  $(dom).remove();
                  children.forEach(function (child) {
                    handleSavedLayout(child);
                  });
                } else {
                  dom.removeAttribute("k-omit");
                }
              } else {
                $(dom)
                  .children()
                  .each(function (idx, component) {
                    handleSavedLayout(component);
                  });
              }
            } else {
              $(dom)
                .children()
                .each(function (idx, component) {
                  handleSavedLayout(component);
                });
            }
          }

          return dom;
        },
        getSaveLayout: function (node, dom) {
          $(node)
            .children()
            .each(function (idx, component) {
              if (component.getAttribute("k-placeholder")) {
                var el = $("<placeholder>");
                $(el).attr("id", component.getAttribute("k-placeholder"));

                if (component.hasAttribute("k-omit")) {
                  $(el).attr("k-omit", "");
                }

                self.getSaveLayout(component, el);
                $(dom).append(el);
              } else if ($(component).parents("[k-placeholder]").length) {
                if (ComponentTool.isNormalComponent(component)) {
                  var el = $("<" + component.tagName.toLowerCase() + ">"),
                    data = $(component).data("kb-comp");
                  $(el).attr(
                    "id",
                    data ? data.name : component.getAttribute("id")
                  );
                  if (component.tagName.toLowerCase() == "layout") {
                    self.getSaveLayout(component, el);
                  }
                  $(dom).append(el);
                } else if (ComponentTool.isEnginedComponent(component)) {
                  var data = $(component).data("kb-comp"),
                    el = $("<" + data.type.toLowerCase() + ">");
                  $(el).attr("engine", data.engine).attr("id", data.name);
                  if (data.type.toLowerCase() == "layout") {
                    self.getSaveLayout(component, el);
                  }
                  $(dom).append(el);
                }
              } else {
                self.getSaveLayout(component, dom);
              }
            });

          return dom;
        },
        getSaveLayoutHTML: function () {
          var vDom = $("<layout>");
          $(vDom).attr("id", self.layoutName);
          vDom = self.getSaveLayout(self.kbFrame.getDocumentElement(), vDom);
          return vDom[0].outerHTML;
        },
        changeType: function (type) {
          if (self.curType !== type) {
            if (type == "code") {
              self.pageContent = html_beautify(self.getLayoutHTML());
              self.backupPageContent = self.pageContent;
            } else {
              if (!self.isPageContentEqual) {
                Kooboo.EventBus.publish("fdoc/load", {
                  fdoc: self.kbFrame.getDocumentElement(),
                  container: $(".kb-editor")[0],
                  positions: self.positions,
                });
              }
            }
            self.curType = type;
          }
        },
        onSaveAndReturn: function () {
          self.isSaveAndReturn = true;
          Kooboo.EventBus.publish("kb/page/save", {});
        },
        onSave: function () {
          self.isSaveAndReturn = false;
          Kooboo.EventBus.publish("kb/page/save", {});
        },
        userCancel: function () {
          if (self.isContentChanged) {
            if (confirm(Kooboo.text.confirm.beforeReturn)) {
              self.goBack();
            }
          } else {
            self.goBack();
          }
        },
        goBack: function () {
          location.href = Kooboo.Route.Get(Kooboo.Route.Page.ListPage);
        },
        onSubmit: function (cb) {
          function submit() {
            Kooboo.Page.post(JSON.stringify(self.submitData)).then(function (
              res
            ) {
              if (res.success) {
                if (typeof cb == "function") {
                  cb(res.model);
                }
              }
            });
          }
          self.posted = true;
          if (!self.valid()) return;
          submit();
        },
      },
      watch: {
        pageContent: function (html) {
          if (html) {
            var layout = $.parseHTML(html, document, true);
            var positions = [];
            positions = self.getPositions(layout, positions, false);
            self.positions = positions;
          }
        },
      },
    });
  })();
</script>
